const tokenHandler = () => {
  return async function (ctx, next) {
    const { app, request } = ctx
    let token = request.header.token || ''
    if (token.indexOf('Bearer') >= 0) {
      token = token.replace('Bearer ', '')
    }
    try {
      const userInfo = app.jwt.verify(token, app.config.jwt.secret)
      ctx.userInfo = userInfo
      // 判断token是否合法，是否有效
      await next()
    } catch (error) {
      console.log('error', error)
      ctx.body = {
        code: '401',
        data: error,
        msg: 'token已失效',
      }
    }
  }
}

export default tokenHandler
